<template>
    <div>
        <el-card class="!border-none" shadow="never">
            <el-alert
                type="warning"
                title="温馨提示：请选择合适的套餐并完成支付"
                :closable="false"
                show-icon
            ></el-alert>
        </el-card>
        <el-card class="!border-none mt-4" shadow="never">
            <el-row :gutter="20">
                <el-col :span="8" v-for="(pkg, index) in packages" :key="index">
                    <el-card
                        class="package-card"
                        :class="{ 'selected-package': selectedPackage?.id === pkg.id }"
                        @click="selectPackage(pkg)"
                    >
                        <h2 class="package-title">{{ pkg.name }}</h2>
                        <div class="package-info">
                            <p class="discount-price">售价：{{ pkg.real_price }}元</p>
                            <p class="original-price">原价：{{ pkg.original_price }}元</p>
                            <p class="points">
                                点券：{{ pkg.buy_cost }}，赠送点券：{{ pkg.send_cost }}
                            </p>
                        </div>
                    </el-card>
                </el-col>
            </el-row>

            <!-- 支付方式 -->
            <div class="payment-methods mt-4">
                <div class="payment-buttons">
                    <div class="payment-button wechat" @click="handleBuy('wechat')"></div>
                    <div class="payment-button alipay" @click="handleBuy('alipay')"></div>
                </div>
            </div>
        </el-card>

        <!-- 支付二维码弹窗（仅用于微信支付） -->
        <el-dialog
            v-model="showQRCodeDialog"
            title="请扫码支付"
            width="400px"
            :before-close="handleDialogClose"
            v-if="payMethod === 'wechat'"
        >
            <div class="text-center">
                <canvas ref="qrCanvas" class="w-[200px] h-[200px] mx-auto"></canvas>
                <p class="mt-4">请使用微信扫码支付</p>
                <p v-if="currentOrderNo" class="mt-2 text-gray-500">订单号: {{ currentOrderNo }}</p>
                <div class="mt-4">
                    <el-button type="primary" @click="refreshQRCode" :loading="refreshing">
                        刷新二维码
                    </el-button>
                </div>
            </div>
        </el-dialog>
    </div>
</template>

<script lang="ts" setup name="interfaceGoodsSaleBuy">
import { ref, onMounted } from 'vue'
import { packageLists, generateQRCode } from '@/api/interface_goods_sale'
import { ElMessage, ElMessageBox } from 'element-plus'
import QRCode from 'qrcode'
import { nextTick } from 'vue'

// 套餐数据
const packages = ref([])
// 支付二维码相关
const showQRCodeDialog = ref(false)
const payMethod = ref('wechat') // 支付方式：wechat 或 alipay
const selectedPackage = ref<any>(null) // 当前选中的套餐
const qrCanvas = ref<HTMLCanvasElement | null>(null) // 二维码canvas引用
const currentOrderNo = ref('') // 当前订单号
const refreshing = ref(false) // 是否正在刷新二维码

// 选择套餐
const selectPackage = (pkg: any) => {
    selectedPackage.value = pkg
}

// 获取套餐列表
const fetchPackages = async () => {
    try {
        const res = await packageLists()
        packages.value = res
    } catch (error) {
        console.error('获取套餐列表失败:', error)
        ElMessage.error('获取套餐列表失败')
    }
}

// 处理支付宝支付表单提交（在新页面打开）
const submitAlipayForm = (formHtml: string) => {
    // 创建一个新窗口
    const newWindow = window.open('', '_blank')
    if (!newWindow) {
        ElMessage.error('无法打开新窗口，请检查浏览器设置')
        return
    }

    // 写入表单HTML到新窗口
    newWindow.document.write(formHtml)
    newWindow.document.close()

    // 使用类型断言解决TS错误
    const forms = newWindow.document.forms as HTMLCollectionOf<HTMLFormElement> & {
        [name: string]: HTMLFormElement
    }

    // 设置超时确保DOM加载完成
    setTimeout(() => {
        const form = forms['alipaysubmit']
        if (form) {
            form.submit()
        } else {
            // 备用方案：使用querySelector
            const fallbackForm = newWindow.document.querySelector(
                'form[name="alipaysubmit"]'
            ) as HTMLFormElement
            if (fallbackForm) {
                fallbackForm.submit()
            } else {
                console.error('无法找到支付宝提交表单')
            }
        }
    }, 100)
}

// 处理购买操作
const handleBuy = async (method: string) => {
    if (!selectedPackage.value) {
        ElMessage.warning('请先选择一个套餐')
        return
    }

    payMethod.value = method

    try {
        const res = await generateQRCode({
            id: selectedPackage.value.id,
            pay_way: method === 'wechat' ? 1 : 2
        })

        currentOrderNo.value = res.order_no || ''

        if (method === 'wechat') {
            // 先显示对话框
            showQRCodeDialog.value = true

            // 使用 nextTick 确保对话框和 canvas 已渲染
            nextTick(() => {
                // 检查 canvas 是否存在
                if (!qrCanvas.value) {
                    console.error('QRCode canvas 未找到')
                    return
                }

                // 检查是否有有效的支付 URL
                if (!res.config) {
                    console.error('无效的支付 URL')
                    return
                }

                generateQRCodeImage(res.config)
            })
        } else {
            submitAlipayForm(res.config)
        }
    } catch (error) {
        console.error('生成支付失败:', error)
        ElMessage.error('生成支付失败')
    }
}

// 生成二维码（仅用于微信支付）
const generateQRCodeImage = (url: string) => {
    if (!qrCanvas.value) return

    QRCode.toCanvas(
        qrCanvas.value,
        url,
        {
            width: 200,
            margin: 2,
            color: {
                dark: '#000000', // 二维码点颜色
                light: '#ffffff' // 背景色
            }
        },
        (error) => {
            if (error) {
                console.error('生成二维码失败:', error)
                ElMessage.error('生成二维码失败')
            }
        }
    )
}

// 刷新二维码（仅用于微信支付）
const refreshQRCode = async () => {
    if (!selectedPackage.value) return

    refreshing.value = true
    try {
        const res = await generateQRCode({
            id: selectedPackage.value.id,
            pay_way: 2 // 微信支付
        })

        currentOrderNo.value = res.order_no || ''
        generateQRCodeImage(res.config)
        ElMessage.success('二维码已刷新')
    } catch (error) {
        console.error('刷新二维码失败:', error)
        ElMessage.error('刷新二维码失败')
    } finally {
        refreshing.value = false
    }
}

// 关闭弹窗时的处理（仅用于微信支付）
const handleDialogClose = (done: () => void) => {
    ElMessageBox.confirm('确定要关闭支付窗口吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    })
        .then(() => {
            done()
        })
        .catch(() => {
            // 取消关闭
        })
}

// 初始化加载套餐列表
onMounted(() => {
    fetchPackages()
})
</script>

<style scoped>
.package-card {
    cursor: pointer;
    transition: all 0.3s;
    margin-bottom: 20px;
    text-align: center;
    padding: 20px;
    border-radius: 8px;
    background-color: #ffffff;
    box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.package-card:hover {
    transform: translateY(-5px);
    box-shadow: 0 10px 20px rgba(0, 0, 0, 0.15);
}

.selected-package {
    border: 2px solid #409eff;
    background-color: #f0f7ff;
}

.package-title {
    color: #303133;
    font-size: 18px;
    font-weight: bold;
    margin-bottom: 15px;
}

.package-info {
    margin-bottom: 15px;
}

.discount-price {
    color: #f56c6c;
    font-size: 16px;
    font-weight: bold;
    margin-bottom: 5px;
}

.original-price {
    color: #909399;
    font-size: 14px;
    text-decoration: line-through;
    margin-bottom: 10px;
}

.points {
    color: #67c23a;
    font-size: 14px;
}

.payment-methods {
    margin-top: 30px;
}

.payment-buttons {
    display: flex;
    justify-content: center;
    gap: 30px;
}

.payment-button {
    width: 120px;
    height: 50px;
    cursor: pointer;
    background-size: contain;
    background-repeat: no-repeat;
    background-position: center;
    transition: all 0.3s;
}

.payment-button:hover {
    transform: scale(1.05);
}

.payment-button.wechat {
    background-image: url('@/assets/images/wechat-pay.png');
}

.payment-button.alipay {
    background-image: url('@/assets/images/alipay.png');
}
</style>